import React, { useState, useEffect } from 'react';
import { Layout, Spin } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import Header from './components/Header';
import HistoryVersions from './components/HistoryVersions';
import Chat from '../chat';
import { SvgIcon } from '@/components/icon';
import { CloseOutlined } from '@ant-design/icons';
import Answer from './components/Answers';

const { Content, Sider } = Layout;


const AppApplication: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [isHistoryMode, setIsHistoryMode] = useState<boolean>(false);
  const [selectedVersion, setSelectedVersion] = useState<string | null>(null);
  const [activeNavKey, setActiveNavKey] = useState<string>('answers');
  const [contentIframe, setContentIframe] = useState<string | null>(null);
  const [iframeLoading, setIframeLoading] = useState<boolean>(false);
  const [showManage, setShowManage] = useState<boolean>(false)



  const toggleHistoryMode = () => {
    setIsHistoryMode(!isHistoryMode);
    setSelectedVersion(null);
  };

  const handleRestoreVersion = () => {
    if (selectedVersion) {
      // 这里添加恢复版本的逻辑
      console.log(`恢复版本: ${selectedVersion}`);
      // 恢复后退出历史模式
      setIsHistoryMode(false);
      setSelectedVersion(null);
    } else {
      console.log('未选择要恢复的版本');
    }
  };

  const handleSelectVersion = (versionId: string) => {
    setSelectedVersion(versionId);
  };

  const handleNavChange = (key: string, path: string) => {

    setActiveNavKey(key);
    if (key === 'answers') {
      setShowManage(false)
      setContentIframe(null);
      return;
    }

    // 加载不同页面到内容区域
    setIframeLoading(true);

    // 获取完整URL路径（将相对路径转为绝对路径）
    const baseUrl = window.location.origin;
    const fullPath = `${baseUrl}${path}`;
    setContentIframe(fullPath);
  };

  const handleIframeLoad = () => {
    setIframeLoading(false);
  };

  const changeManage = () => {
    handleNavChange('knowledge', '/know/datasets/list')
    setShowManage(true)
  };

  return (
    <Layout className="h-screen">
      <Header
        isHistoryMode={isHistoryMode}
        onToggleHistoryMode={toggleHistoryMode}
        onRestoreVersion={handleRestoreVersion}
        onNavChange={handleNavChange}
        showManage={showManage}
      />
      <Layout>
        {activeNavKey === 'answers' ? (
          <>
            <Sider width={400} className="bg-white m-2 border rounded-[20px] border-[#E5E6E8]"
              style={{
                background: '#FBFCFFB2',
              }}
            >
              <div className='p-4 border-b border-[#E5E6E8] mx-2'>
                <div
                  style={{
                    cursor: 'pointer',
                    padding: '10px 20px',
                    background: '#F1F1F1',
                    color: '#6640FF',
                    borderRadius: '8px',
                    display: 'flex',
                    flexDirection: 'column' as const,
                    width: '140px',
                  }}
                >
                  <div className="flex items-center gap-2">
                    <SvgIcon icon="point-all" style={{ fontSize: '20px', }} />
                    <span className="text-[16px] font-medium">知识库</span>
                  </div>
                  <span className={`text-[14px]  text-[#86909C]`}>
                    已设置
                  </span>
                </div>
              </div>
              <div className='p-4 bg-[#EBEDF2] rounded-2xl mx-3 my-4  h-[181px]'>
                <div className='flex  items-center justify-between gap-2'>
                  <div className='font-[600] text-[20px] text-[#131313]'>您是当前应用知识库管理员</div>
                  <CloseOutlined className="text-[#86909C]" />
                </div>
                <div className='my-3 text-[16px]'>可以增加、删除、修改知识库的文件</div>
                <div className='text-[red] text-[16px]'>注意：增加、删除、修改文件后可在问答页面测试，点击“发布”后普通用户的问答内容才会更新</div>
              </div>

              <div className='p-4 bg-[#F6F6F6] mx-3 my-6 rounded-2xl flex items-center justify-between gap-2 h-[91px]'>
                <div className='flex items-center  gap-2'>
                  <SvgIcon icon='point' size={40} color='#8890ff'></SvgIcon>
                  <div className='ml-2 '>
                    <div className=' text-[18px] text-[#131313]'>知识库</div>
                    <div className='text-[14px] text-[#86909C]'>已有5个知识库，共计111个文件</div>
                  </div>
                </div>
                <div className='text-[16px] cursor-pointer text-[#6640FF] font-medium' onClick={() => changeManage()}>管理</div>
              </div>
            </Sider>

            <Content className="m-2 p-4 border  rounded-[20px] border-[#E5E6E8]"
              style={{
                background: '#ECEFF7',
              }}
            >
              <Answer />
            </Content>

            {isHistoryMode && (
              <div className="w-[280px] m-2">
                <HistoryVersions onRestore={handleSelectVersion} />
              </div>
            )}
          </>
        ) : (
          <div className="flex flex-1">
            <Content className="m-2 border rounded-[20px] border-[#E5E6E8] overflow-hidden flex-1"
              style={{
                background: '#FFFFFF',
                position: 'relative',
                height: 'calc(100vh - 64px - 16px)' // 减去头部高度和边距
              }}
            >
              {iframeLoading && (
                <div className="absolute inset-0 flex items-center justify-center bg-white bg-opacity-70 z-10">
                  <Spin size="large" />
                </div>
              )}
              {contentIframe && (
                <iframe
                  src={contentIframe}
                  className="w-full h-full border-none"
                  onLoad={handleIframeLoad}
                />
              )}
            </Content>

            {isHistoryMode && (
              <div className="w-[280px] m-2">
                <HistoryVersions onRestore={handleSelectVersion} />
              </div>
            )}
          </div>
        )}
      </Layout>
    </Layout>
  );
};

export default AppApplication; 